package dao;

import entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import utils.SqlHelper;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class UserDao {
    private SqlSessionFactory sqlSessionFactory;
    public UserDao() throws IOException {
        sqlSessionFactory = SqlHelper.getSqlSessionFactory();
    }

    public User getUserById(int id) {
        User user = null;
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            user = sqlSession.selectOne("test.mapper.selectUserById", id);
        }
        finally {
            return user;
        }
    }

    public List<User> getAllUser() {
        try(SqlSession sqlSession =sqlSessionFactory.openSession()) {
            List<Object> result = sqlSession.selectList("test.mapper.selectAllUser");
            List<User> users = new LinkedList<>();
            for (Object user:
                 result) {
                users.add((User) user);
            }
            return users;
        }
    }

    private int baseUpdateUser(User user, String statement) {
        int result = 0;
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            result = sqlSession.update(statement, user);
            sqlSession.commit();
        }
        return result;
    }

    public int insertUser(User user) {
        return baseUpdateUser(user, "test.mapper.insertUser");
    }

    public int updateUser(User user) {
        return baseUpdateUser(user, "test.mapper.updateUser");
    }

    public int deleteUser(User user) {
        return baseUpdateUser(user, "test.mapper.deleteUser");
    }

}
